package com.ruoyi.project.app.service;


import ai.advance.cmp.api.client.bean.ResponseBean;
import ai.advance.cmp.api.client.bean.dto.TrafficUserDTO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.ruoyi.common.support.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.project.app.util.CalculationUtil;
import com.ruoyi.project.app.util.CardUtil;
import com.ruoyi.project.app.util.XException;
import com.ruoyi.project.beautyflower.BfUtil;
import com.ruoyi.project.beautyflower.ThreeElementsUtil;
import com.ruoyi.project.beautyflower.loanApplication.domain.LoanApplication;
import com.ruoyi.project.beautyflower.loanApplication.mapper.LoanApplicationMapper;
import com.ruoyi.project.beautyflower.loanPurpose.domain.LoanPurpose;
import com.ruoyi.project.beautyflower.loanPurpose.mapper.LoanPurposeMapper;
import com.ruoyi.project.beautyflower.member.domain.Member;
import com.ruoyi.project.beautyflower.member.mapper.MemberMapper;
import com.ruoyi.project.beautyflower.order.domain.Order;
import com.ruoyi.project.beautyflower.order.mapper.OrderMapper;
import com.ruoyi.project.beautyflower.paymentHistory.domain.PaymentHistory;
import com.ruoyi.project.beautyflower.paymentHistory.mapper.PaymentHistoryMapper;
import com.ruoyi.project.beautyflower.stagingMonths.domain.StagingMonths;
import com.ruoyi.project.beautyflower.stagingMonths.mapper.StagingMonthsMapper;
import com.ruoyi.project.beautyflower.userBankcard.domain.UserBankcard;
import com.ruoyi.project.beautyflower.userBankcard.mapper.UserBankcardMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 用户公共层
 */
@Service
public class AppMyService {

    @Autowired
    private MemberMapper memberMapper;//用户信息mapper
    @Autowired
    private LoanPurposeMapper loanPurposeMapper;//借款用途mapper
    @Autowired
    private StagingMonthsMapper stagingMonthsMapper;//分期月数
    @Autowired
    private UserBankcardMapper userBankcardMapper;//用户绑定银行卡
    @Autowired
    private LoanApplicationMapper loanApplicationMapper;//借款申请记录表

    @Autowired
    private OrderMapper orderMapper;//订单mapper

    @Autowired
    private PaymentHistoryMapper paymentHistoryMapper;//还款记录



    /**
     * 实名认证
     * @param params
     * @return
     */
    public int setNameAuthentication(Map<String, String> params){
        Map<String,Object> userMap= Maps.newHashMap();
        int count=0;
        userMap.put("name",params.get("name"));
        userMap.put("phoneNumber",params.get("mobile"));
        userMap.put("idCardNumber",params.get("carId"));
        Member member=new Member();
        member.setId(Integer.parseInt(params.get("userId")));
        member.setName(params.get("name"));
        member.setMobile(params.get("mobile"));
        member.setCarId(params.get("carId"));
        member.setAuthenticationStatus(2);
        ResponseBean responseBean=ThreeElementsUtil.threeElementsVerification(userMap);
        if(responseBean.getCode().equals("000000")){
//            if(count>0){
                try {
                    Map<String,Object> carMap= Maps.newHashMap();
                    if(member.getCarId().length()==18){
                        carMap=CardUtil.getCarInfo(member.getCarId());
                    }else{
                        carMap=CardUtil.getCarInfo15W(member.getCarId());
                    }
                    TrafficUserDTO users=new TrafficUserDTO();
                    users.setUserId(member.getId()+"");
                    users.setIdNumber(member.getCarId());
                    users.setName(member.getName());
                    users.setMobileNumber(member.getMobile());
                    users.setGender(carMap.get("sex")+"");
                    member.setSex(Integer.valueOf(carMap.get("sex1")+""));
                    member.setBarthDate(carMap.get("birthDate")+"");
                    count=memberMapper.updateMember(member);
                    //在本地实名认证成功后，调用第三方接口进行数据保存
                    ResponseBean responseBean1=  BfUtil.createTrafficUser(users);
                    System.out.println(responseBean1.getCode());
                    System.out.println(responseBean1.getMessage());
                    System.out.println(responseBean1.getData());
                    if(responseBean1.getCode().equals("SUCCESS")){
                        return 1;
                    }else{
                        return 0;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
//            }
        }else{
            throw new XException("三要素信息验证失败");
        }
        return count;
    }


    /**
     * 查询借款用途设置列表
     * @return 借款用途设置集合
     */
    public List<LoanPurpose> selectLoanPurposeList(){
        return loanPurposeMapper.selectLoanPurposeList(new LoanPurpose());
    }

    /**
     * 查询分期月数设置列表
     * @return 分期月数设置集合
     */
    public List<StagingMonths> selectStagingMonthsList(){
        return stagingMonthsMapper.selectStagingMonthsList(new StagingMonths());
    }

    /**
     * 用户绑定银行卡
     * @param map
     * @return
     */
    public ResponseBean insertBackCard(Map<String,String> map){
        UserBankcard userBankcard=userBankcardMapper.selectUserBankcardByBankCardNumber(map.get("backCardNumber"),"0");
        if(userBankcard==null){
            throw new XException("银行卡号错误");
        }

        if(userBankcard!=null&&!userBankcard.getBankCardName().equals(map.get("backCardName"))){
            throw new XException("银行卡名称不匹配");
        }
        ResponseBean responseBean=BfUtil.confirmBindCardAuthDemo(map);
        if(responseBean.getCode().equals("SUCCESS")){
            userBankcard.setStatus(1);
            userBankcardMapper.updateUserBankcard(userBankcard);
        }
        return responseBean;
    }

    /**
     * 根据用户id查询银行卡列表
     * @param userId
     * @return
     */
    public List<UserBankcard> selectUserBankcardByUserId(String userId){
        return userBankcardMapper.selectUserBankcardByUserId(userId);
    }
    /**
     * 用户借款申请记录添加
     * @param userId
     * @return
     */
    public int insertLoanApplication(String userId){
        LoanApplication loanApplication =new LoanApplication();
        loanApplication.setUserId(Integer.valueOf(userId));
        loanApplication.setCreateTime(new Date());
        return loanApplicationMapper.insertLoanApplication(loanApplication);
    }
    /**
     * 借款申请审核结果
     * @param userId
     * @return
     */
    public Map<String,String> auditResults(String userId){
        Map<String,String> map=Maps.newHashMap();
        ResponseBean responseBean=BfUtil.queryCreditLineResult(userId);//用户额度查询
        Order order=orderMapper.selectOrderByIdMemberId(userId);
        List<LoanApplication> loanApplicationList=loanApplicationMapper.selectLoanApplicationByUsetId(Integer.valueOf(userId));
        if(loanApplicationList!=null&&loanApplicationList.size()>0){
            LoanApplication loanApplication=loanApplicationList.get(0);
            loanApplication.setUpdateTime(new Date());
            loanApplicationMapper.updateLoanApplication(loanApplication);
            map.put("borrowingTime",loanApplication.getCreateTime().getTime()+"");//借款申请时间
//            map.put("createAt",order.getUpdateDate()+"");//线上审核时间
            map.put("createAt",loanApplication.getUpdateTime().getTime()+"");//线上审核时间
            if(order!=null){
                map.put("orderTime",order.getOrderTime());
            }else{
                map.put("orderTime","");
            }
        }
        return map;
    }

    /**
     * 保存用户头像
     * @param map
     * @return
     */
    public Member updateHeadImg(Map<String,String> map){
        Map<String,String> maps=Maps.newHashMap();
       Member member= memberMapper.selectMemberById(Integer.parseInt(map.get("userId")));
        member.setLogo(map.get("logo_url"));
        memberMapper.updateMember(member);
//        maps.put("id",map.get("userId"));
//        maps.put("name",map.get("name"));
//        maps.put("sex",map.get("sex"));
//        maps.put("barthDate",map.get("barthDate"));
//        maps.put("logo",map.get("logo_url"));
        return member;
    }
    /**
     * 用户删除银行卡
     * @param back_id
     * @return
     */
    public int deleteUserBankcardById(String back_id){
        return userBankcardMapper.deleteUserBankcardByIds(Convert.toStrArray(back_id));
    }
    /**
     * 查询个人用户信息
     * @param userId
     * @return
     */
    public Member selectMemberById(Integer userId){
        return memberMapper.selectMemberById(userId);
    }


    /**
     * 更新在线审核时间
     * @param userId
     * @param date
     * @return
     */
    public int updateLoanApplication(String userId,String date,String status){
        List<LoanApplication> loanApplicationList=loanApplicationMapper.selectLoanApplicationByUsetId(Integer.valueOf(userId));
        LoanApplication loanApplication=loanApplicationList.get(0);
        if(loanApplicationList!=null && loanApplicationList.size()>0){
            try {
                loanApplication.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(DateUtils.longToDate((Long.parseLong(date)))));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
//        updateApplyDate(userId,status,date);
        return  loanApplicationMapper.updateLoanApplication(loanApplication);
    }
    /**
     * 更新在线审核时间
     * @param userId
     * @param status
     * @return
     */
    public int updateApplyDate(String userId,String status,String date){
        Member member=memberMapper.selectMemberById(Integer.valueOf(userId));
        if(member!=null){
            member.setApplyDate(date);
            member.setApplyStatus(Integer.valueOf(status));
        }
        return  memberMapper.updateMember(member);
    }

    /**
     * 增还款记录
     * @param memberId
     * @param bankCardNumber
     * @param bankName
     * @param details
     */
    public void insertPaymentHistory(int memberId,String  bankCardNumber,String bankName,String paymentNo, String details){
        JSONArray jsonArray = JSON.parseArray(details);
        SimpleDateFormat ymdFormat = new SimpleDateFormat("yyyyMMdd");
        String dateFormat = ymdFormat.format(new Date());
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONArray jsonArray1=jsonArray.getJSONArray(i);
            for (int i1 = 0; i1 < jsonArray1.size(); i1++) {
                String overdueFee = "0";
                String nowPayTime = dateFormat;//当前时间
                JSONObject jsonObject = (JSONObject) jsonArray1.get(i1);
                PaymentHistory paymentHistory=new PaymentHistory();
                paymentHistory.setOrderId(jsonObject.getString("orderId")+"");//订单id
                paymentHistory.setInstallmentNo(jsonObject.getString("installmentNo"));//还款分期号
                paymentHistory.setDuePrincipalAmount(jsonObject.getBigDecimal("duePrincipalAmount"));//应还款本金
                paymentHistory.setRepaymentInterestAmount(jsonObject.getBigDecimal("repaymentInterestAmount"));//应还款利息
                paymentHistory.setRepaymentPrincipalAmount(jsonObject.getBigDecimal("duePrincipalAmount"));//实际还款本金
                paymentHistory.setStatus("ONGOING");
                paymentHistory.setRepaymentTime(DateUtils.getTime());
                paymentHistory.setMemberId(memberId);
                paymentHistory.setBankCardNumber(bankCardNumber);
                paymentHistory.setBankName(bankName);
                paymentHistory.setPaymentNo(paymentNo);
                if (Integer.valueOf(jsonObject.getString("dueDate"))>=Integer.valueOf(nowPayTime)) {
                    paymentHistory.setBeOverdue(BigDecimal.valueOf(0L));
                }else{
                    try {
                        int days = CalculationUtil.differentDays(ymdFormat.parse(nowPayTime), ymdFormat.parse(jsonObject.getString("dueDate")));
                        overdueFee= CalculationUtil.handleSubStr(overdueFee, CalculationUtil.handleMulStr(String.valueOf(Double.valueOf(jsonObject.getBigDecimal("duePrincipalAmount")+"")*0.001), String.valueOf(days), 2), 2);
                        paymentHistory.setBeOverdue(new BigDecimal(overdueFee));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                paymentHistoryMapper.insertPaymentHistory(paymentHistory);
//                Order order=orderMapper.selectOrderByListOrderNumber(jsonObject.getString("orderId"));
//                if(order!=null&&!order.getStatus().equals("ONGOING")){
//                    order.setStatus("ONGOING");
//                    orderMapper.updateOrder(order);
//                }
            }
        }
    }
}
